package com.epam.command.load;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.epam.command.logic.Command;
import com.epam.dao.DAOFactory;
import com.epam.dao.DAOFactory.DAOType;
import com.epam.dao.intf.DAO;
import com.epam.entity.AbstractEntity;
import com.epam.util.ConfigurationManager;

public class LoadAllPurchasesCommand implements Command {

	
	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) {
		
		String address = request.getParameter("address");
		String page = ConfigurationManager.getConfig(address);
		
		int pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
		int numberOfRecords = Integer.parseInt(ConfigurationManager.getConfig(ConfigurationManager.NUMBER_OF_RECORDS_ON_PAGE));
		int offset = (pageNumber - 1)*numberOfRecords; 
		List<AbstractEntity> purchases;
		DAO purchasedao = DAOFactory.INSTANCE.getDAO(DAOType.PURCHASE);
		
		purchases = purchasedao.findAllPaginated(offset, numberOfRecords);
		
		int purchaseCount = purchasedao.findAll().size();
		int numberOfPages = (int) Math.ceil((double)purchaseCount/numberOfRecords);
		
		
		
		request.setAttribute("pageNumber", pageNumber);
		request.setAttribute("numberOfPages", numberOfPages);
		request.setAttribute("entityList", purchases);
		
		
		return page;
		
	}

}
